package com.it.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.entity.insure.AiInsureOrder;
import com.it.mapper.AiInsureOrderMapper;
import com.it.service.AiInsureOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.R;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 投保单表 服务实现类
 * </p>
 *
 * @author yzy
 * @since 2025年09月17日
 */
@Service
public class AiInsureOrderServiceImpl extends ServiceImpl<AiInsureOrderMapper, AiInsureOrder> implements AiInsureOrderService {

    @Autowired
    private AiInsureOrderMapper aiInsureOrderMapper;

    @Override
    public R addInsureOrder(AiInsureOrder aiInsureOrder) {
        try {
            // 生成保单编号
            String policyNo = generatePolicyNo();

            // 设置必要字段
            aiInsureOrder.setPolicyId(policyNo);
            aiInsureOrder.setCreateTime(LocalDateTime.now());
            // 可以根据业务需求设置其他默认值，如保单状态
            aiInsureOrder.setPolicyStatus(1); // 1表示新建状态
            // 执行插入操作
            aiInsureOrderMapper.insert(aiInsureOrder);

            return R.Success("保单新增成功", aiInsureOrder.getOrderId());
        } catch (Exception e) {
            log.error("新增保单失败", e);
            return R.Failed("新增保单失败：" + e.getMessage());
        }
    }

    @Override
    public R list(int pageNum, int pageSize, String policyId, String insuredId, String insuranceCoverageName, Integer policyStatus,Integer payStatus) {

        // 使用PageHelper设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 创建LambdaQueryWrapper，使用Lambda表达式避免硬编码字段名
        LambdaQueryWrapper<AiInsureOrder> queryWrapper = new LambdaQueryWrapper<>();

        // 保单编号模糊查询（忽略空值）
        if (StringUtils.isNotBlank(policyId)) {
            queryWrapper.like(AiInsureOrder::getPolicyId, policyId);
        }

        // 投保人ID模糊查询（忽略空值）
        if (StringUtils.isNotBlank(insuredId)) {
            queryWrapper.like(AiInsureOrder::getInsuredId, insuredId);
        }

        // 险种名称精确匹配（忽略空值）
        if (StringUtils.isNotBlank(insuranceCoverageName)) {
            queryWrapper.eq(AiInsureOrder::getInsuranceCoverageName, insuranceCoverageName);
        }

        // 保单状态精确匹配（忽略空值）
        if (policyStatus != null) {
            queryWrapper.eq(AiInsureOrder::getPolicyStatus, policyStatus);
        }

        // 保单支付状态精确匹配（忽略空值）
        if (payStatus != null) {
            queryWrapper.eq(AiInsureOrder::getPayStatus, payStatus);
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc(AiInsureOrder::getCreateTime);

        // 执行查询，PageHelper会自动拦截并处理分页
        List<AiInsureOrder> policyList = aiInsureOrderMapper.selectList(queryWrapper);

        return R.Success("查询成功", new PageInfo<>(policyList));
    }

    @Override
    public R delete(Integer id) {
        if (id == null) {
            return R.Failed("该数据不存在");
        }
        aiInsureOrderMapper.deleteById(id);
        return R.Success("删除成功");
    }

    @Override
    public R get(Integer id) {
        if (id == null) {
            return R.Failed("该数据不存在");
        }
        return R.Success("查看成功", aiInsureOrderMapper.selectById(id));
    }

    @Override
    public R update(AiInsureOrder aiInsureOrder) {
        if (aiInsureOrder == null){
            return R.Failed("该数据不存在");
        }AiInsureOrder aiInsureOrder1 = aiInsureOrder;
        if(aiInsureOrder.getOrderId()==null&&aiInsureOrder.getPolicyId()!=null){
            LambdaQueryWrapper<AiInsureOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AiInsureOrder::getPolicyId, aiInsureOrder.getPolicyId());
            aiInsureOrder1 = aiInsureOrderMapper.selectOne(queryWrapper);
            aiInsureOrder1.setPayStatus(3);
            aiInsureOrder1.setPolicyStatus(2);
        }
        aiInsureOrderMapper.updateById(aiInsureOrder1);
        return R.Success("修改状态成功");
    }

    @Override
    public AiInsureOrder getOrderByPolicyId(String policyId) {
        LambdaQueryWrapper<AiInsureOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiInsureOrder::getPolicyId, policyId);
        return aiInsureOrderMapper.selectOne(queryWrapper);
    }

    /**
     * 生成保单编号
     * 格式：INS+yyyyMMdd+6位随机数，例如：INS20250918123456
     */
    private String generatePolicyNo() {
        // 前缀
        String prefix = "POL";
        // 日期部分：年月日
        String datePart = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 随机数部分：6位随机数
        String randomPart = String.format("%06d", new Random().nextInt(1000000));

        // 组合生成保单编号
        return prefix + datePart + randomPart;
    }

}


